package com.northpool.operator.common.json;

import com.alibaba.fastjson.JSONPath;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "JsonPathOperator",
        name = "Json解析",
        description = "解析JSON并抽取其中值"
)
@OutputParams({
        @OutputParam(ref = "execResult", name = "数据抽取结果", type = TypeEnum.STRING)
})
public class JsonPathOperator  extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "jsonStr", name = "JSON字符串", desc = "JSON字符串,如: {\"name\":\"test\"}", required = true),
            @InputParam(ref = "exec", name = "表达式", desc = "JsonPath表达式,文档地址: http://northpool.work:6807/ZvVXBz6XYE ", required = true)
    })
    public JsonPathOperator() {
    }

    public static void main(String[] args) {

    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String jsonStr = paramTool.getStr("jsonStr");
        String exec = paramTool.getStr("exec");

        JSONPath jsonPath = new JSONPath(exec);
        Object val = jsonPath.eval(jsonStr);

        String execResult = "";
        if (val instanceof String) {
            execResult = (String) val;
        } else if (val instanceof Number) {
            execResult = String.valueOf(val);
        } else if(val != null){
            throw new RuntimeException("暂不支持的数据抽取结果类型： " + execResult.getClass().getName());   
        }
        this.result("execResult", execResult);
    }

}
